<template>
  <div class="container">
    <div class="page-header">
      <h1 class="page-title">区块链投资管理平台</h1>
      <p class="page-subtitle">安全、透明地管理您的区块链投资记录</p>
    </div>
    
    <!-- 加载中提示 -->
    <div v-if="loading" class="loading-container">
      <div class="spinner-border custom-spinner" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
      <p class="loading-text">正在从区块链获取投资记录...</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="alert alert-danger">
      <i class="bi bi-exclamation-triangle-fill me-2"></i>
      {{ error }}
    </div>
    
    <!-- 搜索和操作面板 -->
    <div class="custom-card action-panel">
      <div class="card-body">
        <div class="row align-items-center">
          <div class="col-md-7 mb-3 mb-md-0">
            <div class="search-container">
            <div class="input-group">
                <span class="input-group-text search-icon">
                  <i class="bi bi-search"></i>
                </span>
                <input 
                  type="text" 
                  class="form-control custom-form-control search-input" 
                  placeholder="搜索投资ID或交易哈希..." 
                  v-model="searchQuery"
                  @keyup.enter="search"
                >
                <button class="custom-btn custom-btn-primary" @click="search">
                  查询
              </button>
              </div>
              <small class="search-hint">提示: 输入数字ID或以0x开头的交易哈希</small>
            </div>
          </div>
          <div class="col-md-5 text-md-end">
            <router-link to="/create" class="custom-btn custom-btn-primary create-btn">
              <i class="bi bi-plus-circle"></i> 创建新投资
            </router-link>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 投资列表 -->
    <div v-if="investments.length > 0" class="investment-list">
      <div class="custom-card investment-card" v-for="investment in investments" :key="investment.id" :class="{'inactive-card': !investment.isActive}">
        <div class="card-header">
          <div class="d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center">
              <span class="investment-id">ID: {{ investment.id }}</span>
              <span v-if="!investment.isActive" class="custom-badge bg-danger ms-2">已删除</span>
            </div>
            <div class="investment-amount">
              <i class="bi bi-coin me-1"></i>
              <span>{{ investment.amount }}</span>
            </div>
          </div>
        </div>
        <div class="card-body">
          <div class="investment-info">
            <div class="info-section">
              <div class="info-row">
                <div class="info-label"><i class="bi bi-briefcase me-2"></i>项目:</div>
                <div class="info-value">{{ investment.projectName }}</div>
              </div>
              <div class="info-row">
                <div class="info-label"><i class="bi bi-building me-2"></i>行业:</div>
                <div class="info-value">{{ investment.profession }}</div>
              </div>
              <div class="info-row">
                <div class="info-label"><i class="bi bi-person me-2"></i>投资人:</div>
                <div class="info-value">{{ investment.investor }}</div>
              </div>
            </div>
            <div class="info-section">
              <div class="info-row">
                <div class="info-label"><i class="bi bi-fingerprint me-2"></i>数据哈希:</div>
                <div class="info-value hash-value">{{ shortenHash(investment.dataHash) }}</div>
              </div>
              <div class="info-row">
                <div class="info-label"><i class="bi bi-link-45deg me-2"></i>交易哈希:</div>
                <div class="info-value hash-value">{{ shortenHash(investment.txHash) }}</div>
              </div>
              <div class="info-row">
                <div class="info-label"><i class="bi bi-toggle-on me-2"></i>状态:</div>
                <div class="info-value" :class="investment.isActive ? 'text-success' : 'text-danger'">
                  <i :class="investment.isActive ? 'bi bi-check-circle-fill' : 'bi bi-x-circle-fill'" class="me-1"></i>
                  {{ investment.isActive ? '有效' : '已删除' }}
                </div>
              </div>
            </div>
          </div>
          <div class="action-buttons">
            <router-link :to="`/detail/${investment.id}`" class="custom-btn custom-btn-info">
              <i class="bi bi-info-circle"></i> 详情
            </router-link>
            <router-link v-if="investment.isActive" :to="`/edit/${investment.id}`" class="custom-btn custom-btn-warning">
              <i class="bi bi-pencil"></i> 编辑
            </router-link>
            <button v-if="investment.isActive" @click="confirmDelete(investment.id)" class="custom-btn custom-btn-danger">
              <i class="bi bi-trash"></i> 删除
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 没有数据时显示 -->
    <div v-else-if="!loading" class="custom-card empty-state">
      <div class="card-body text-center p-5">
        <div class="empty-icon">
          <i class="bi bi-journal-x"></i>
        </div>
        <h3 class="empty-title">暂无投资记录</h3>
        <p class="empty-text">创建您的第一条区块链投资记录，开始追踪您的投资历史</p>
        <div class="mt-4">
          <router-link to="/create" class="custom-btn custom-btn-primary btn-lg">
          <i class="bi bi-plus-circle"></i> 创建新投资
        </router-link>
        </div>
      </div>
    </div>
    
    <!-- 确认删除的模态框 -->
    <div v-if="showModal" class="modal-overlay">
      <div class="custom-modal">
          <div class="modal-header">
          <h5 class="modal-title">
            <i class="bi bi-exclamation-triangle me-2 text-warning"></i>
            确认删除
          </h5>
            <button type="button" class="btn-close" @click="showModal = false"></button>
          </div>
          <div class="modal-body">
          <p>您确定要删除ID为 <strong>{{ deleteId }}</strong> 的投资记录吗？</p>
          <div class="alert alert-warning">
            <i class="bi bi-info-circle me-2"></i>
            <small>此操作是软删除，记录仍将保留在区块链上，但标记为无效。此操作无法撤销。</small>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="custom-btn custom-btn-secondary" @click="showModal = false">
            <i class="bi bi-x"></i> 取消
          </button>
          <button type="button" class="custom-btn custom-btn-danger" @click="deleteInvestment">
            <i class="bi bi-trash"></i> 确认删除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, ref, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import '../assets/styles.css';

export default {
  name: 'HomeView',
  setup() {
    const store = useStore();
    const router = useRouter();
    
    // 响应式数据
    const searchQuery = ref('');
    const showModal = ref(false);
    const deleteId = ref(null);
    
    // 计算属性
    const investments = computed(() => store.getters.allInvestments);
    const loading = computed(() => store.getters.isLoading);
    const error = computed(() => store.getters.errorMessage);
    
    // 方法
    const fetchInvestments = async () => {
      await store.dispatch('fetchInvestments');
    };
    
    const search = async () => {
      const query = searchQuery.value.trim();
      
      if (!query) {
        return;
      }
      
      // 判断是ID还是交易哈希
      if (/^\d+$/.test(query)) {
        // 如果是数字，当作ID查询
        const result = await store.dispatch('fetchInvestmentById', query);
        if (result) {
          router.push(`/detail/${query}`);
        }
      } else if (/^(0x)?[0-9a-fA-F]{64}$/.test(query)) {
        // 如果是64位16进制，当作交易哈希查询
        const txHash = query.startsWith('0x') ? query : `0x${query}`;
        const result = await store.dispatch('getInvestmentByTxHash', txHash);
        if (result) {
          router.push(`/detail/${result.id}`);
        } else {
          store.commit('SET_ERROR', '未找到匹配的投资记录');
        }
      } else {
        store.commit('SET_ERROR', '无效的查询格式。请输入投资ID或交易哈希');
      }
    };
    
    const confirmDelete = (id) => {
      deleteId.value = id;
      showModal.value = true;
    };
    
    const deleteInvestment = async () => {
      if (deleteId.value) {
        const success = await store.dispatch('deleteInvestment', deleteId.value);
        if (success) {
          showModal.value = false;
          deleteId.value = null;
        }
      }
    };
    
    const shortenHash = (hash) => {
      if (!hash) return '';
      
      // 将16进制字节数组转换为字符串
      let hashStr = '';
      if (Array.isArray(hash)) {
        // 转换字节数组为16进制字符串
        hashStr = '0x' + Array.from(hash).map(b => b.toString(16).padStart(2, '0')).join('');
      } else if (typeof hash === 'string') {
        hashStr = hash.startsWith('0x') ? hash : `0x${hash}`;
      } else {
        return 'Invalid hash';
      }
      
      // 截取前6位和后4位
      return `${hashStr.substring(0, 8)}...${hashStr.substring(hashStr.length - 6)}`;
    };
    
    // 组件挂载时获取投资列表
    onMounted(fetchInvestments);
    
    return {
      investments,
      loading,
      error,
      searchQuery,
      showModal,
      deleteId,
      search,
      confirmDelete,
      deleteInvestment,
      shortenHash
    };
  }
}
</script>

<style scoped>
.home-container {
  animation: fadeIn 0.5s ease-out;
  background-color: var(--cream-yellow);
  padding: 1.5rem;
  border-radius: 16px;
}

.page-header {
  margin-bottom: 2.5rem;
}

.page-subtitle {
  color: var(--secondary-color);
  margin-top: -0.5rem;
  font-size: var(--font-size-md);
}

.loading-container {
  text-align: center;
  padding: 3rem;
  background-color: var(--white);
  border-radius: 16px;
  box-shadow: 0 4px 14px var(--shadow-color);
}

.loading-text {
  margin-top: 1.5rem;
  color: var(--secondary-color);
  font-size: var(--font-size-md);
}

.action-panel {
  margin-bottom: 2rem;
}

.search-container {
  position: relative;
}

.search-icon {
  background-color: transparent;
  border-right: none;
  color: var(--secondary-color);
}

.search-input {
  border-left: none;
  padding-left: 0;
}

.search-hint {
  position: absolute;
  left: 44px;
  bottom: -20px;
  color: var(--secondary-color);
  font-size: var(--font-size-xs);
}

.create-btn {
  padding: 0.7rem 1.8rem;
}

.investment-list {
  display: grid;
  gap: 1.5rem;
}

.investment-card {
  transition: all 0.3s ease;
}

.inactive-card {
  opacity: 0.7;
}

.investment-id {
  font-size: var(--font-size-md);
  font-weight: 600;
  color: var(--dark-text);
}

.investment-amount {
  background-color: var(--accent-color);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-weight: 600;
  font-size: var(--font-size-sm);
}

.investment-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.info-row {
  display: flex;
  margin-bottom: 0.8rem;
}

.info-label {
  font-weight: 500;
  color: var(--secondary-color);
  width: 110px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  font-size: var(--font-size-sm);
}

.info-value {
  flex: 1;
  font-size: var(--font-size-base);
}

.hash-value {
  font-family: monospace;
  background-color: var(--light-cream);
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  font-size: var(--font-size-sm);
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 0.8rem;
  margin-top: 1.2rem;
  padding-top: 1.2rem;
  border-top: 1px solid var(--border-color);
}

.empty-state {
  padding: 3rem;
}

.empty-icon {
  font-size: 4rem;
  color: var(--secondary-color);
  opacity: 0.3;
  margin-bottom: 1.5rem;
}

.empty-title {
  font-weight: 600;
  margin-bottom: 1rem;
  font-size: var(--font-size-xl);
}

.empty-text {
  color: var(--secondary-color);
  max-width: 500px;
  margin: 0 auto;
  font-size: var(--font-size-md);
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1050;
}

.custom-modal {
  background-color: var(--white);
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.modal-body {
  padding: 1.8rem;
  font-size: var(--font-size-base);
}

.modal-footer {
  padding: 1.5rem;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  border-top: 1px solid var(--border-color);
}

@media (max-width: 768px) {
  .investment-info {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .info-row {
    margin-bottom: 0.6rem;
  }
  
  .action-buttons {
    justify-content: center;
  }
}
</style> 